from django.shortcuts import render
from django.views import View
from .models import *
from django.core.paginator import Paginator
import math
from django.http import HttpResponse

# Create your views here.

class IndexView(View):
    def get(self,request,category_id=2,page=1):
        category_id =  int(category_id)
        page = int(page)
        # 1.获取所有的商品类别信息
        category_list = Category.objects.all().order_by('id')
        # 2.获取某个类别下的所有的商品信息
        goods_list = Goods.objects.filter(category_id=category_id).order_by('id')
        # 3.添加分页功能
        paginatorObj = Paginator(goods_list, 8)
        page_goods_obj = paginatorObj.page(page)
        # 4.添加页码数
        satrt = page - math.ceil(10/2)
        if satrt < 1:
            satrt = 1
        end = satrt + 9
        if end > paginatorObj.num_pages:
            end = paginatorObj.num_pages
        if end < 10:
            satrt = 1
        else:
            satrt = end - 9
        page_list = range(satrt,end+1)
        return render(request,'index.html',{'category_list':category_list,'goods_list':page_goods_obj,'current_category':category_id,'page_list':page_list})

def recommend(func):
    def _wrapper(detailView, request, goods_id, *args, **kwargs):
        # 获取cookie里用户访问过的商品ID列表('1 2 3')
        c_goods_id = request.COOKIES.get('c_goods_id', '')

        # 存放用户访问过的商品ID列表
        goods_id_list = [str(id) for id in c_goods_id.split() if id.strip()]

        # 存放用户访问过的商品对象列表
        current_goods_category = Goods.objects.get(id=goods_id).category_id
        goods_obj_list = [Goods.objects.get(id=gid) for gid in goods_id_list if gid != str(goods_id) and Goods.objects.get(id=gid).category_id == current_goods_category][:4]

        # 更新用户访问的商品ID列表
        if str(goods_id) in goods_id_list:
            goods_id_list = [id for id in goods_id_list if id != str(goods_id)]
            goods_id_list.insert(0, str(goods_id))
        else:
            goods_id_list.insert(0, str(goods_id))

        # 调用视图方法
        response = func(detailView, request, goods_id, recommend_list=goods_obj_list, *args, **kwargs)

        # 将用户访问过的商品ID列表存放到Cookie中    2 1 3 4
        response.set_cookie('c_goods_id', ' '.join(map(str, goods_id_list)), max_age=3 * 24 * 60 * 60)

        return response

    return _wrapper


class DetailView(View):
    @recommend
    def get(self,request,goods_id,recommend_list=[]):
        goods_id = int(goods_id)

        # 1.根据商品ID获取商品详细信息
        try:
            goods = Goods.objects.get(id=goods_id)
            return render(request,'detail.html',{'goods':goods,'recommend_list':recommend_list})
        except Goods.DoesNotExist:
            return HttpResponse(status=404)
        

